package com.gxh.controller.user;


import com.gxh.constant.JwtClaimsConstant;
import com.gxh.dto.UserDTO;
import com.gxh.dto.UserLoginDTO;
import com.gxh.entity.User;
import com.gxh.properties.JwtProperties;
import com.gxh.result.Result;
import com.gxh.service.UserService;
import com.gxh.utils.JwtUtil;
import com.gxh.vo.UserLoginVO;
import com.gxh.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController("userUserController")
@RequestMapping("/gxh/user/user")
@Slf4j
@Api(tags = "用户管理")
public class UserController {


    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信用户登入
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信用户登入")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("微信登录：{}", userLoginDTO);
        //调用微信登入接口获取到唯一的openid
        User user = userService.wxLogin(userLoginDTO);
        //创建哈希集合
        Map<String, Object> claims = new HashMap<>();
        //将用户id放入
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        //创建jwt令牌
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 修改用户信息
     * @param userDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody UserDTO userDTO) {
        log.info("修改用户信息：{}", userDTO);
        userService.update(userDTO);
        return Result.success();
    }

    /**
     * 查询用户信息
     * @return
     */
    @GetMapping
    @ApiOperation("查询用户信息")
    public Result<UserVO> get() {
        log.info("查询用户信息");
        UserVO userVO = userService.getById();
        return Result.success(userVO);
    }

    @DeleteMapping
    @ApiOperation("用户注销")
    public Result delete() {
        log.info("用户注销");
        userService.deleteById();
        return Result.success();
    }
}
